#!/usr/bin/env python
# -*- coding: utf-8 -*-

import json
import sys
import time
from datetime import datetime

import requests

reload(sys)
sys.setdefaultencoding('utf-8')


class DingtalkRobot(object):
    '''
    将统计结果发送给钉钉
    '''

    def __init__(self, write_robot_f):
        '''
        @param write_robot_f: 文件句柄，用于记录机器人发送的日志
        '''
        self.write_robot_f = write_robot_f

    def send_msg_to_dd(self, web_hook_url, title, mk_text):
        '''
        发送mk_text到钉钉
        @param web_hook_url: 机器人链接  str
        @param title: 主题名  str
        @param mk_text: 钉钉内容  str
        @return: None
        '''

        msg_body = {
            "msgtype": "markdown",
            "markdown": {
                "title": title,
                "text": mk_text
            },
        }
        headers = {
            "Content-Type": "application/json;charset=utf-8"
        }
        retry_count = 0
        self.write_robot_f.write("\n\n\n{}\n{}\n".format(mk_text, datetime.now()))
        while retry_count < 10:
            try:
                response = requests.post(url=web_hook_url, data=json.dumps(msg_body), headers=headers)
                if response.status_code == 200:
                    self.write_robot_f.write("{} 发送钉钉信息成功：{}\n".format(datetime.now(), response.status_code))

                    break
                else:
                    self.write_robot_f.write("{}  返回状态码不正常：{}\n".format(datetime.now(), response.status_code))
            except Exception as e:
                self.write_robot_f.write("{}  请求异常：{}\n".format(datetime.now(), e))
                retry_count += 1
                time.sleep(2)
            self.write_robot_f.flush()

    def main(self, web_hook_url, title, mk_text):
        '''
        暴露给外部使用，进行机器人发送
        @param web_hook_url:
        @param title:
        @param mk_text:
        @return:
        '''
        self.send_msg_to_dd(web_hook_url, title, mk_text)
        self.write_robot_f.flush()
